package com.xbongbong.pro.statistics.strategy.chart.type.impl;

import com.xbongbong.paas.constant.XbbConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.pro.bi.commons.pojo.vo.GroupSqlVO;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartAnalysisVO;
import com.xbongbong.pro.statistics.help.AggregationlHelper;
import com.xbongbong.pro.statistics.help.ChartGraphVOHelper;
import com.xbongbong.pro.statistics.help.CommonHelper;
import com.xbongbong.pro.statistics.help.DisplayHelper;
import com.xbongbong.pro.statistics.help.InitSqlHelper;
import com.xbongbong.pro.statistics.pojo.dto.ChartAnalysisDTO;
import com.xbongbong.pro.statistics.pojo.dto.GenerateSqlDTO;
import com.xbongbong.pro.statistics.pojo.vo.GenerateSqlVO;
import com.xbongbong.pro.statistics.strategy.chart.type.ChartTypeStrategyService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.pro.statistics.help.InitSqlHelper.getIsMaxPermission;


/**
 * 大部分统计图，除了单独渲染的
 *
 * @author xinpeng.jiang
 * @version V1.0
 * @date 2021/5/17 10:00
 * @since V1.0
 */
@Service
public class ChartStrategyServiceImpl implements ChartTypeStrategyService {
    @Resource
    private InitSqlHelper initSqlHelper;
    @Resource
    private AggregationlHelper aggregationlHelper;
    @Resource
    private CommonHelper commonHelper;
    @Resource
    private DisplayHelper displayHelper;
    @Resource
    private ChartGraphVOHelper chartGraphVOHelper;
    public Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public ChartAnalysisVO chartAnalysis(ChartAnalysisDTO chartAnalysisDTO) throws XbbException {
        Map<String, Map<String, String>> attrLinkMap = aggregationlHelper.getLinkMap(chartAnalysisDTO.getChartEntity(),  chartAnalysisDTO.getResultArray());
        return chartGraphVOHelper.chartGraphAnalysis(chartAnalysisDTO,attrLinkMap);
    }



    @Override
    public GenerateSqlVO generateSql(GenerateSqlDTO generateSqlDTO) throws XbbException {
        GenerateSqlVO generateSqlVO = new GenerateSqlVO();
        ChartEntity chartEntity = generateSqlDTO.getChartEntity();
        if (chartEntity.getChartClassify().size() <= 0 || chartEntity.getChartValue().size() <= 0) {
            return generateSqlVO;
        }
        ChartResultPojo chartResultPojo = generateSqlDTO.getChartResultPojo();
        boolean isSingle = generateSqlDTO.getSingle();
        StringBuffer stringBuffer = new StringBuffer();
        Map<Long, String> formIdTableMap = commonHelper.getFormIdTableMap(chartEntity, isSingle);
        //筛选+查询
        Map<String,StringBuffer>  fliterMap = new HashMap<>(XbbConstant.INITIALCAPACITY);
        initSqlHelper.parseConditionIntersection(fliterMap, chartEntity, false);
        Map<String, String> sortFieldMap = displayHelper.getAggSortMap(chartEntity, chartResultPojo.getSortStatisticsMap(),chartResultPojo.getSortFieldOrder());
        //聚合条件 要放置两份，一份在colums,一份在group BY
        Pair<GroupSqlVO, HashMap<String, Set<String>>> groupSqlVOHashMapPair = aggregationlHelper.chartAggregationsBuilder(chartEntity, formIdTableMap, sortFieldMap);
        GroupSqlVO groupSqlVO = groupSqlVOHashMapPair.getKey();
        List<String> groupFieldsList = groupSqlVO.getGroupFieldsList();
        List<String> aggFieldsList = groupSqlVO.getAggFieldsList();
        List<String> groupColumnsList  = groupSqlVO.getGroupColumnsList();
        StringBuilder gropuColumns  = new StringBuilder();
        for (int i = 0; i < groupColumnsList.size(); i++) {
            gropuColumns.append(groupColumnsList.get(i));
            if(i != groupColumnsList.size()-1){
                gropuColumns.append(",");
            }
        }
        StringBuilder gropuFields  = new StringBuilder();
        for (int i = 0; i < groupFieldsList.size(); i++) {
            gropuFields.append(groupFieldsList.get(i));
            if(i != groupFieldsList.size()-1){
                gropuFields.append(",");
            }
        }
        StringBuffer aggFields  = new StringBuffer();
        for (int i = 0; i < aggFieldsList.size(); i++) {
            aggFields.append(aggFieldsList.get(i));
            if(i != aggFieldsList.size()-1){
                aggFields.append(",");
            }
        }
        if(CollectionUtils.isNotEmpty(groupColumnsList)){
            if(CollectionUtils.isNotEmpty(aggFieldsList)){
                aggFields.append(",");
            }
            aggFields.append(gropuColumns);
        }
        //构建子查询外层SQL语句的返回字段
        initSqlHelper.buildSubColumnOfCount(groupSqlVO,groupColumnsList,Boolean.TRUE);

        String sortField = displayHelper.getAggSortField(sortFieldMap,groupSqlVO);
        boolean isMaxPermission = getIsMaxPermission(chartResultPojo);
        initSqlHelper.tableJoin(groupSqlVOHashMapPair,chartEntity, isSingle, stringBuffer, aggFields, sortField, fliterMap, 100, 0,gropuFields.toString(),isMaxPermission);
        //分页  TODO
        PageHelper pageHelper = new PageHelper(1);
        generateSqlVO.setPageHelper(pageHelper);
        generateSqlVO.setStringBufferSql(stringBuffer);
        generateSqlVO.setAggFieldMap(groupSqlVO.getAggFieldMap());
        return generateSqlVO;
    }
}
